/**
 * 
 */
package any.radeox;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import any.radeox.Outline.Entry;

/**
 * @author keke
 * @version $Revision: 21 $
 */
public class SimpleOutlineController implements OutlineController {
	private static final Logger	LOG	= LoggerFactory
	                                        .getLogger(SimpleOutlineController.class);
	private Outline	            outline;

	/*
	 * (non-Javadoc)
	 * 
	 * @see any.note.radeox.OutlineController#addHeader(java.lang.String,
	 *      java.lang.String)
	 */
	public String addHeader(final String headerLevel, final String title) {
		final int level = Integer.valueOf(headerLevel);
		final Entry entry = new Entry();
		entry.level = level;
		entry.name = title;
		entry.headers = new Integer[level];
		if (LOG.isDebugEnabled()) {
			LOG.debug("To add header {}", headerLevel + "-" + title);
		}
		if (outline == null) {
			outline = new Outline();
			outline.getRoot().add(entry);

			for (int i = 0; i < level; i++) {
				entry.headers[i] = 1;
			}
			outline.setCurrent(entry);
		} else {
			final Entry current = outline.getCurrent();
			if (LOG.isDebugEnabled()) {
				LOG.debug("Current level: {}", current.getHeaderName());
			}
			for (int i = 0; i < entry.headers.length; i++) {
				int h = 1;
				if (level - 1 == i && current.headers.length > i) {
					h = current.headers[i] + 1;
				} else if (current.headers.length > i) {
					h = current.headers[i];
				}
				entry.headers[i] = h;
			}

			addToParent(current, entry);
			outline.setCurrent(entry);
		}
		return entry.getHeaderName();
	}

	private void addToParent(final Entry parent, final Entry entry) {
		if (parent.level < entry.level) {
			parent.add(entry);
		} else {
			addToParent(parent.parent, entry);
		}
	}

}
